import * as jwt from "jsonwebtoken";

const qualifyURL = (url, encode) => {
  url = url || "";
  var ret =
    location.protocol +
    "//" +
    location.host +
    (url.substr(0, 1) === "/" ? "" : location.pathname.match(/.*\//)) +
    url;
  if (encode) {
    ret = encodeURIComponent(ret);
  }
  return ret;
};

const getCookie = (name) => {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2)
    return parts
      .pop()
      .split(";")
      .shift();
};

const AUTH_SERVER = "https://sso.sohu-inc.com/login";
const APP_ID = "ba80f81d-5281-4272-9d0f-6a7c1e880296";
const SSO_TOKEN_KEY = "sns_sso_cookie";

export const goSSO = (hash) => {
  const reurl = `/competition/${hash}`;
  const redirectURL =
    AUTH_SERVER + "?appid=" + APP_ID + "&reurl=" + qualifyURL(reurl, true);
  location.href = redirectURL;
};

export const getSSOTokenInfo = () => {
  try {
    const ssoCookie = getCookie(SSO_TOKEN_KEY);
    if (ssoCookie) {
      return jwt.decode(ssoCookie);
    } else {
      goSSO(location.hash);
    }
  } catch (err) {
    goSSO(location.hash);
  }
};

export const getHashQuery = (key, qs = location.hash) => {
  const queryString = qs.split("?")[1];
  if (!queryString) {
    return;
  }
  const tokens = queryString.split("&");
  const queries = {};
  for (var i = 0; i < tokens.length; i++) {
    var nv = tokens[i].split("=");
    if (!nv[0]) continue;
    queries[nv[0]] = decodeURIComponent(nv[1]) || true;
  }
  return queries[key];
};
